import { userLogin,userInfo,userLogout } from "../../api/auth/auth";
import { setToken,getToken, removeToken,setUser,getUser,removeUser } from "../../utils/cookie"

const state = {
    token: getToken(),
    user: getUser(),
}

const mutations = {
    SET_TOKEN(state,token){
        state.token = token
    },
    SET_USER(state,user){
        state.user = user
    }
}

const actions = {
    //用户登陆
    login({ commit },ruleForm){
        // console.log(ruleForm);
        return new Promise((resolve,reject)=>{
            userLogin(ruleForm.username.trim(),ruleForm.password).then(res=>{
                const result = res.data;
                commit("SET_TOKEN",result.data);
                setToken(result.data);
                resolve(result);
            }).catch(error=>{
                reject(error);
        })
        });
    },
    //获取用户信息
    info({ commit,state }){
        return new Promise((resolve,reject)=>{
            userInfo().then(res=>{
                const result = res.data;
                console.log(result.data);
                if(!result.data){
                    commit("SET_TOKEN","");
                    commit("SET_USER",null);
                    // removeAll();
                    resolve(result);
                    reject("Verification failed, please Login again.");
                }
                commit("SET_USER",result.data);
                //将用户存到本地localStorage
                setUser(result.data);
                resolve(result.data);
            })
        }).catch(error=>{
            reject(error);
        })
    },
    //退出登陆
    logout({ commit }){
        return new Promise((resolve,reject)=>{
            userLogout().then(res=>{
                const result = res.data;
                commit("SET_TOKEN","");
                commit("SET_USER",null);
                removeToken();
                removeUser();
                resolve(result);
            }).catch(error=>{
                reject(error);
            });
        })
    }

}

const user = {
    state,
    mutations,
    actions
}
export default user